package cxy.highConcurrency;

import java.util.concurrent.Semaphore;

/**
 * 用信号量保证互斥
 * @author admin
 *
 */
public class SemaphoreDemo {

	static int count;
	//初始化信号量
	static final Semaphore s = new Semaphore(1);

	//用信号量保证互斥    
	static void addOne()  {
		try {
			s.acquire();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		try {
			count += 1;
			System.out.println(Thread.currentThread().getName() + ",count:" + count);
		} finally {
			s.release();
		}
	}
	
	
	
	public static void main(String[] args) {
		Thread t1 = new Thread(() -> {
			for (int i = 0; i < 100; i++) {
				addOne();
			}
		});
		
		Thread t2 = new Thread(() -> {
			for (int i = 0; i < 100; i++) {
				addOne();
			}
		});
		
		t1.start();
		t2.start();
	}

}
